package com.atguigu.tingshu.search.listener;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.Assert;
import java.time.Duration;
import java.util.List;

@Slf4j
public class DistroBloomFilterInitListener implements SpringApplicationRunListener {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        boolean containsBean = context.containsBean("rBloomFilter");
        if (containsBean) {
            RBloomFilter rBloomFilter = context.getBean("rBloomFilter", RBloomFilter.class);
            long count = rBloomFilter.count();
            if (count == 0) {
                ItemServiceImpl itemServiceImpl = context.getBean("itemServiceImpl", ItemServiceImpl.class);
                Result<List<Long>> albumIds = itemServiceImpl.getAlbumIds();
                List<Long> albumIdsData = albumIds.getData();
                Assert.notNull(albumIdsData, "远程调用获取专辑Id列表失败");
                rBloomFilter.add(albumIdsData);
//                rBloomFilter.add(10000L);
                logger.info("分布式布隆过滤器数据初始化完毕，且元素个数为：{}", rBloomFilter.count());
            }
        }
    }
}

